package cl.mt.proxy;

import java.io.Serializable;
import java.util.Collection;
import java.util.Iterator;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import cl.mt.data.DataRegion;
import cl.mt.dto.DTORegion;

public class ProxyRegion implements Serializable {

	private static final long serialVersionUID = 1L;
	private transient Logger log = LogManager.getLogger(ProxyRegion.class.getName());

	private static ProxyRegion instance = null;
	private static Collection<DTORegion> lista = null;

	public ProxyRegion() {
	}

	public static ProxyRegion getInstance() {
		if (instance == null) {
			instance = new ProxyRegion();
		}
		return instance;
	}

	public DTORegion getById(Integer id) {
		if (id == null)
			return null;
		if (lista == null)
			findAll();

		if (lista != null)
			for (Iterator<DTORegion> it = lista.iterator(); it.hasNext();) {
				DTORegion dto = (DTORegion) it.next();
				if (id.equals(dto.getId()))
					return dto;
			}

		return null;
	}

	private void findAll() {
		DataRegion dao = new DataRegion();
		lista = dao.findAll();
		log.debug("Cargando Todos los Registros");
	}

	public void refresh() {
		lista = null;
		log.debug("Refresh Proxy");
	}

	public Collection<DTORegion> getLista() {
		if (lista == null)
			findAll();
		return lista;
	}

	public String getNombre(Integer id) {
		DTORegion dto = getById(id);

		return dto != null ? dto.getDescripcion() : null;
	}

}
